package com.suse.service.admin.statistics.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suse.common.config.response.ApiException;
import com.suse.common.config.response.R;
import com.suse.common.util.date.DateUtil;
import com.suse.service.admin.statistics.entity.Daily;
import com.suse.service.admin.statistics.feign.AdminUserService;
import com.suse.service.admin.statistics.mapper.DailyMapper;
import com.suse.service.admin.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-22
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

    @Resource
    private AdminUserService adminUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R createStatisticsByDate(String date) {

        // 如果当日统计信息已存在则删除
        Integer count = lambdaQuery().eq(Daily::getDateCalculated, date).count();
        if (count > 0) {
            lambdaUpdate().eq(Daily::getDateCalculated,date).remove();
        }
        // 注册数
        R registerCountR = adminUserService.getDailyRegisterCount(date);
        // 以下为 mock 数据
        int loginCount = RandomUtil.randomInt(100, 200);
        int videoViewCount = RandomUtil.randomInt(100, 200);
        int courseCount = RandomUtil.randomInt(100, 200);

        // 封装为 Daily 对象
        Daily daily = new Daily();
        daily.setDateCalculated(date);
        daily.setRegisterCount((Integer) ((Map<String,Object>)registerCountR.getData()).get("registerCount"));
        daily.setLoginCount(loginCount);
        daily.setVideoViewCount(videoViewCount);
        daily.setCourseCount(courseCount);

        // 插入到数据库
        if (save(daily)) {
            return R.success("统计信息生成成功");
        }else {
            throw new ApiException("统计信息生成失败！");
        }

    }

    @Override
    public R getChartData(LocalDate[] dateScope) {
        // 获取注册统计数
        Map<String, Object> registerCount = getCountData("register_count", dateScope);
        // 获取登录统计数
        Map<String, Object> loginCount = getCountData("login_count", dateScope);
        // 获取视频播放统计数
        Map<String, Object> videoViewCount = getCountData("video_view_count", dateScope);
        // 获取新增课程统计数
        Map<String, Object> courseCount = getCountData("course_count", dateScope);
        // 封装为一个 map
        HashMap<String, Map<String, Object>> map = new HashMap<>();
        map.put("registerCount",registerCount);
        map.put("loginCount",loginCount);
        map.put("videoViewCount",videoViewCount);
        map.put("courseCount",courseCount);
        return R.put("chartData",map).success();
    }

    private Map<String,Object> getCountData(String column,LocalDate[] dateScope) {
        LocalDate begin = dateScope[0];
        LocalDate end = dateScope[1];
        List<LocalDate> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();
        DateUtil.datesUntil(begin,end).forEach((date) -> {
            xData.add(date);
            QueryWrapper<Daily> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(column);
            queryWrapper.eq("date_calculated",date);
            List<Object> values = baseMapper.selectObjs(queryWrapper);
            if (CollectionUtil.isEmpty(values)) {
                yData.add(0);
            }else {
                yData.add((Integer) values.get(0));
            }
        });
        HashMap<String, Object> map = new HashMap<>();
        map.put("xData",xData);
        map.put("yData",yData);
        return map;
    }

}
